package m.jclecai.com.view.klpk;

/**
 * Created by andy on 2017/7/12.
 */


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.bean.klpk.bean.PokerBean;

/**
 * 用来实现poker机选的效果的；
 * 我们希望通过这个类，能够实现的一个效果就是，不管是这个Demo还是真实的项目，
 * 我们都通过这个类而不用修改代码；
 */
public class KLPKRandomEffect {

    private static final String ASSET_SOUND = "sound";
    public View  mBottomPoker;        //最下面的bottomView;
    public List<View>  mCenterPokers;       //中间的poker

    public List<View> mDestView;

    public Context mContext;
    private SoundPool mSoundPool;
    private ArrayList<Integer> mSoundIdList;


    public KLPKRandomEffect(View bottomPoker, List<View> centerPokers, Context context) {
        mBottomPoker = bottomPoker;
        mCenterPokers = centerPokers;
        mContext = context;

        initSound();
    }


    public void start(){
        openPokerAnimation();
    }

    /**
     * 这里的话，是初始化声音；
     */
    private void initSound() {

        mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
        mSoundIdList = new ArrayList<>();
        loadSound();
    }

    private void loadSound() {
        AssetManager assets = mContext.getAssets();

        String[] soundNames=null;
        try {
            //获取assets目录下面的sound目录下面的所有的声音的名字；
            soundNames = assets.list(ASSET_SOUND);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (String soundName : soundNames) {
            //这里我们将初始化得到soundId；
            try {
                AssetFileDescriptor afd = assets.openFd("sound"+"/"+soundName);
                int soundId = mSoundPool.load(afd, 1);
                mSoundIdList.add(soundId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private void openPokerAnimation() {

        if (mOnAnimatorListnener != null) {
            mOnAnimatorListnener.onAnimatorStart();
        }

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mBottomPoker.getLayoutParams();
        int bottomMargin = layoutParams.bottomMargin;

        //1、让底部显示出来；
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBottomPoker, "TranslationY", 0, bottomMargin);//这个100是bottom的一个margin值
        objectAnimator.setDuration(200);

        objectAnimator.start();

        objectAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                startTransAnimation2();
            }
        });

        //2、发射poker
        //3、旋转poker     //底部隐藏
        //4、poker移动到指定的位置；//缩小和移动的动画；
    }

    /**
     * 从左到右依次设置每张牌的牌型
     * @param strings
     */
    public void setCenterPokers(List<PokerBean> strings){
        for (int i = 0; i < mCenterPokers.size(); i++) {
            View view = mCenterPokers.get(i);
           // ((TextView) view.findViewById(R.id.tv_poker_text)).setText(strings.get(i));
            RandomPoker randomPoker = (RandomPoker) view.findViewById(R.id.ep_poker);
            randomPoker.setPoker(strings.get(i));
        }
    }

    /**
     *
     *从左到右依次，设置某张牌移动到具体的哪个位置；
     * @param destView
     */
    public void setDestView(List<View> destView){
        this.mDestView=destView;
    }



    public void startTransAnimation2(){

        AnimatorSet animatorSet=new AnimatorSet();
        List<Animator> animators=new ArrayList<>();
        for (int i = 0; i < mCenterPokers.size(); i++) {
            View view = mCenterPokers.get(i);
            Animator animator = transAnimatorSet(view);
            animator.setStartDelay(i*200);

            animators.add(animator);
        }
        animatorSet.playTogether(animators);
        animatorSet.start();

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //执行反转的动画；
                rotateAnimation2();
                closePokserAnimation();
            }
        });
    }


    public void closePokserAnimation(){

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mBottomPoker.getLayoutParams();
        int bottomMargin = layoutParams.bottomMargin;

        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBottomPoker, "TranslationY",bottomMargin,0);
        objectAnimator.setDuration(200);
        objectAnimator.start();
    }


    //发射的poker动画
    public Animator transAnimatorSet(View view){

        Animator.AnimatorListener animatorListener=new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mSoundPool.play(mSoundIdList.get(2), 1.0f, 1.0f, 1, 0, 1.5f);
            }
        };


        int measureHeight = getMeasureHeight(view);
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int height = windowManager.getDefaultDisplay().getHeight();
        int moveDistance = ((height - measureHeight) / 2)-height;

        ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(view, "TranslationY", 0, moveDistance);
        objectAnimator1.addListener(animatorListener);
        return objectAnimator1;
    }


    /**
     * 对View的一个宽高测量；
     * @param view
     * @return
     */
    public int  getMeasureHeight(View view){

        int measureSpec = View.MeasureSpec.makeMeasureSpec((1 << 30) - 1, View.MeasureSpec.AT_MOST);
        view.measure(measureSpec,measureSpec);
        return view.getMeasuredHeight();
    }


    public void rotateAnimation2(){

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 180);

        valueAnimator.setDuration(1200);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float animatedValue = (Float) animation.getAnimatedValue();

                for (View pokerView : mCenterPokers) {
                    pokerView.setRotationY(animatedValue);
                }

                if (animatedValue.intValue()==90) {
                    //等于90°的时候让textView显示；
                    //在这里我们设置让牌显示；
                    for (View pokerView : mCenterPokers) {
                       // pokerView.findViewById(R.id.tv_poker_text).setVisibility(View.VISIBLE);
                        pokerView.findViewById(R.id.ep_poker).setVisibility(View.VISIBLE);
                        pokerView.findViewById(R.id.iv_img).setVisibility(View.INVISIBLE);
                    }

                }else if(animatedValue.intValue()==0){
                    mSoundPool.play(mSoundIdList.get(1),0.5f ,0.5f ,1 ,0 ,1.0f);
                }else if(animatedValue==180){
                    mSoundPool.play(mSoundIdList.get(0),1.0f ,1.0f ,1 ,0 ,1.0f);
                }
            }
        });

        valueAnimator.start();

        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                dispearPokerAnimation2();
            }
        });
    }
    /**
     * 将牌移动到具体的矩形的中间的位置；
     * 这里我们需要将方法改一下，这里我们之前的逻辑是这样的就是，让所有的牌移动的到一个位置。
     * 这里的话，
     * 我们要实现的逻辑是这样的，可以移动到同一个位置，也可以分散移动到不同的位置；
     */
    public void dispearPokerAnimation2(){
        if(mDestView.size()==1){
            //这里表示所有的牌飞到一个地方
            for (int i = 0; i < mCenterPokers.size(); i++) {
                Rect rect=new Rect();
                mDestView.get(0).getGlobalVisibleRect(rect);
                dispearAnimation(mCenterPokers.get(i),rect);
            }
        }else{
            //所有的牌各自飞到自己的位置；
            for (int i = 0; i < mCenterPokers.size(); i++) {
                Rect rect=new Rect();
                mDestView.get(i).getGlobalVisibleRect(rect);
                dispearAnimation(mCenterPokers.get(i),rect);
            }
        }
    }


    private void dispearAnimation(View poker,Rect rectDest) {
        AnimatorSet animatorSet=new AnimatorSet();

        ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(poker, "ScaleX", 1, 0f).setDuration(500);
        ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(poker, "ScaleY", 1, 0f).setDuration(500);

        int destX = rectDest.left + rectDest.width()/2;
        int destY = rectDest.top + rectDest.height()/2;


        Rect rect=new Rect();
        poker.getGlobalVisibleRect(rect);

        int pokerCenterX = rect.left + poker.getWidth()/2;
        int pokerCenterY = rect.top  + poker.getHeight()/2;
        int dx = destX - pokerCenterX;
        int dy = destY - pokerCenterY;

        int measureHeight = getMeasureHeight(poker);
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int height = windowManager.getDefaultDisplay().getHeight();
        int moveDistance = ((height - measureHeight) / 2)-height;


        //这里的话，我们是需要计算这个牌到这个具体位置的dx和dy
        ObjectAnimator objectAnimator3 = ObjectAnimator.ofFloat(poker, "TranslationX", 0, dx).setDuration(500);
        ObjectAnimator objectAnimator4 = ObjectAnimator.ofFloat(poker, "TranslationY", moveDistance, dy+moveDistance).setDuration(500);

        animatorSet.playTogether(objectAnimator1,objectAnimator2,objectAnimator3,objectAnimator4);

        animatorSet.setStartDelay(500);
        animatorSet.start();

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                resetAnimation();

                if (mOnAnimatorListnener != null) {
                    mOnAnimatorListnener.onAnimatorEnd();
                }
            }
        });
    }

    private void resetAnimation() {
        //这里这里对其poker进行一个还原；
        for (View centerPoker : mCenterPokers) {

            centerPoker.setTranslationY(0);
            centerPoker.setTranslationX(0);
            centerPoker.setRotationY(0);

           // centerPoker.findViewById(R.id.tv_poker_text).setVisibility(View.INVISIBLE);
            centerPoker.findViewById(R.id.ep_poker).setVisibility(View.INVISIBLE);
            centerPoker.findViewById(R.id.iv_img).setVisibility(View.VISIBLE);

            centerPoker.setScaleY(1);
            centerPoker.setScaleX(1);
        }
    }

    public interface OnAnimatorListnener{
        void onAnimatorStart();
        void onAnimatorEnd();
    }

    public OnAnimatorListnener mOnAnimatorListnener;

    public void setOnAnimatorListnener(OnAnimatorListnener onAnimatorListnener) {
        mOnAnimatorListnener = onAnimatorListnener;
    }

    public void resease(){
        mSoundPool.release();
    }
}
